package org.drushpal.model
{
	import flash.data.EncryptedLocalStore;
	import flash.net.registerClassAlias;
	import flash.utils.ByteArray;
	
	import mx.collections.ArrayCollection;
	
	import org.drushpal.view.forms.ConnectionEvent;
	import org.drushpal.model.vo.Connection;
	import org.robotlegs.mvcs.Actor;
	
	public class ConnectionModel extends Actor
	{
		[Bindable]
		public var connections:ArrayCollection;
		public function ConnectionModel()
		{			
			registerClassAlias("Connection",Connection);
			var storageCon:ByteArray = EncryptedLocalStore.getItem("connections");			
			if(storageCon){
				connections = storageCon.readObject() as ArrayCollection;
			}else{
				connections = new ArrayCollection();
			}
		}
		
		
		private function flushEncryptedData():void{				
			var data:ByteArray = new ByteArray();
			data.writeObject(connections);
			EncryptedLocalStore.setItem("connections",data);
		}
		
		
		public function saveConnection(connection:Connection):void{
			var bFound:Boolean = false;
			for each(var con:Connection in connections){
				if(con.uuid == connection.uuid){
					bFound = true;
					con = connection;
					break;
				}
			}
			if(!bFound) connections.addItem(connection);
			flushEncryptedData();
		}
		public function removeConnection(connection:Connection):void{
			var size:int = connections.length;
			for(var i:int = 0; i < size; i++){
				if(Connection(connections.getItemAt(i)).uuid == connection.uuid){
					connections.removeItemAt(i);
					break;
				}
			}
			flushEncryptedData();
		}
		
	}
}